import ObserverList from './observer'
import { $msg } from '@/core/msg.js'
import { getIMToken } from '@/service/im'
import Chat from './chat.js'

/**
 * 实例化IM
 */
export default function(im) {
	let chat = Chat(im)
	let statusWatcher = new ObserverList();

	let disconnect = () => {
		console.log('断开IM链接');
		chat.clearMsgCount()
		im.unwatch()
		im.disconnect();
	};

	let connect = async () => {
		try {
			let token = await getIMToken()
			im.watch({
				status({ status }) {
					if (status === 0) chat.getChatList()
					statusWatcher.notify(status);
				},
			})
			return await im.connect({ token });
		} catch (e) {
			console.log('消息服务连接失败');
		}
	};

	let watchStatus = (watch) => {
		statusWatcher.add(watch);
	};

	return {
		disconnect,
		connect,
		watchStatus,
	};
};
